package com.jarvis.hospital;

import android.Manifest;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jarvis.hospital.common.AppManager;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.FileResponseData;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.LoginActivity;
import com.jarvis.hospital.login.model.FileModel;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.MainPatientActivity;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.AddressManager;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ImageActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_right)
    RelativeLayout rel_right;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.ivHead)
    ImageView ivHead;

    private ApiService service;
    private String photo_path;
    private FileModel fileModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_imgage;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        rel_left.setOnClickListener(this);
        rel_right.setOnClickListener(this);
        rel_right.setVisibility(View.VISIBLE);
        ivHead.setOnClickListener(this);
        tv_title.setText("修改头像");
        tv_right.setText("保存");
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        Glide.with(this)
                .load(userModel.getUserHeadImg())
                .error(R.drawable.img_main_bg)
                .into(ivHead);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_left:
                finish();
                break;
            case R.id.ivHead:
                new RxPermissions(ImageActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    //所有权限都开启aBoolean才为true，否则为false
                                    PhotoPicker.builder()
                                            .setPhotoCount(1)
                                            .setShowCamera(true)
                                            .setShowGif(true)
                                            .setPreviewEnabled(false)
                                            .start(ImageActivity.this, 1);
                                } else {
                                    showTextToast("请选择允许使用权限");
                                }
                            }
                        });

                break;
            case R.id.rel_right:
                if(fileModel==null){
                    finish();
                }else {
                    updateUserInfo();
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            if (data != null) {
                final ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photo_path = photos.get(0);
                upImage(1);
            }
        }
    }
    private void upImage(final int type) {
        showDialog("loading");
        final String url = AddressManager.getFileHost();
        ApiService service_phone = RequestApi.create(ApiService.class, url);
        File file = new File(photo_path);//filePath 图片地址
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("folderName", "changzheng");//ParamKey.TOKEN 自定义参数key常量类，即参数名
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("files", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

        List<MultipartBody.Part> parts = builder.build().parts();

        Call<FileResponseData<List<FileModel>>> call = service_phone.uploadImage(parts);
        call.enqueue(new Callback<FileResponseData<List<FileModel>>>() {
            @Override
            public void onResponse(Call<FileResponseData<List<FileModel>>> call, Response<FileResponseData<List<FileModel>>> response) {
                disMiss();
                if (response.body() != null) {
                    int statusCode = response.body().getCode();
                    if (statusCode == 200) {
                        Glide.with(ImageActivity.this)
                                .load(photo_path)
                                .centerCrop()
                                .into(ivHead);
                        fileModel=response.body().getResult().get(0);
                    } else {
                        showTextToast(response.body().getDesc());
                    }
                } else {
                    showTextToast("请求失败");
                }
            }

            @Override
            public void onFailure(Call<FileResponseData<List<FileModel>>> call, Throwable t) {
                disMiss();
                showTextToast(RequestApi.detailError(t));
            }
        });
    }
    public void updateUserInfo() {
        showDialog("加载中");
        service = RequestApi.create(ApiService.class);
        service.updateUserInfo(fileModel.getFilePath())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData responseData) {
                        if (responseData != null) {
                            int resultCode = responseData.getResultCode();
                            if (resultCode == 200) {
                                showTextToast("修改成功");
                                //final String url = AddressManager.getFileHost();
                                LoginModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class);
                                UserModel userInfo = userModel.getUserInfo();
                                userInfo.setUserHeadImg("http://118.31.11.83:8049/upload/"+fileModel.getFilePath());
                                SharePreferenceUtils.putObject(SharePreferenceKey.LOGIN_MODEL, userModel);
                                finish();
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });

    }
}
